
##################################################
## Human Trafficking Indicators: A New Dataset ##
## Author: Richard W Frank                     ##
## Journal: International Interactions         ##
## Code written: April 2021                    ##
## Software: rstan ver. 2.15.1, R ver. 3.3.1   ##
## Purpose: Running dynamic IRT model          ## 
#################################################

 
rm(list=ls())
setwd("~")

library(rstan)
library(loo)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
library(dplyr)
library(bayesplot)
library(rstanarm)
library(ggplot2)
 
## load processed data
load("HTI_stan_data_prepped.RData")

model <- c("M2_dynamic")

deg_free <- rep(4, length(prev_id))
deg_free[prev_id==0] <- 3000

stan.data$deg_free = deg_free

########################
## stan dynamic model ##
########################

fit <- stan(file=paste(model, ".stan", sep=""), data=stan.data, warmup=1000, iter=2000, 
            chains=4, cores=4, verbose=T, pars=c("theta_raw", "r_year_raw","r_country_raw"), 
            include = F, seed = 123456789)

## once it is run then I save various parts of the output for future study.
save.image("hti_dynamic.RData")
output <- rstan::extract(fit, permuted = TRUE)
save(output, file="hti_dynamic_output.RData")


